package com.bw.controller;

import com.bw.entity.*;
import com.bw.mapper.StudentMapper;
import com.bw.service.StudentService;
import org.spring.kun.common.ExcelUtils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@Controller
public class HouseController {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    StudentService studentService;


    @RequestMapping("/list.do")
    public String list(StudentQuery query, Model model, HttpServletRequest request) {

        // 获取当前登录用户
        User user = TokenUtils.getLoginUserFromRequest(request, User.class);
        model.addAttribute("name", user.getName());
        model.addAttribute("nickName", user.getNickName());
        model.addAttribute("avatarUrl", user.getAvatarUrl());

        // 执行查询
        List<StudentRoom> list = studentMapper.selectByParam(query);
        model.addAttribute("list", list);

        return "list";
    }

    @RequestMapping("/excelList.do")
    public void excelList(StudentQuery query, HttpServletResponse response) {

        List<StudentRoom> list = studentMapper.selectByParam(query);
        ExcelUtils.exportExcel(list, "学生入住信息导出", "sheet1", response);
    }


    @RequestMapping("/addPage.do")
    public String addPage(Model model) {

        // 渲染下拉框
        List<Dict> stuList = studentMapper.listStudent();
        model.addAttribute("stuList", stuList);
        List<Dict> roomList = studentMapper.listRoom();
        model.addAttribute("roomList", roomList);
        List<Dict> apartmentList = studentMapper.listApartment();
        model.addAttribute("apartmentList", apartmentList);
        return "add";
    }

    @RequestMapping("/add.do")
    public String add(@Valid StudentRoomAdd studentRoomAdd, BindingResult result,Model model){

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            // 渲染下拉框
            List<Dict> stuList = studentMapper.listStudent();
            model.addAttribute("stuList", stuList);
            List<Dict> roomList = studentMapper.listRoom();
            model.addAttribute("roomList", roomList);
            List<Dict> apartmentList = studentMapper.listApartment();
            model.addAttribute("apartmentList", apartmentList);
            return "add";
        }
        studentService.add(studentRoomAdd);

        // 给学生发短信
        ZzyUtils.sendSms("17611221735","你已成功入住",5);

        return "redirect:list.do";
    }
}
